<script setup lang="ts">
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, h, ref, onBeforeMount } from 'vue'
import { Page, useVbenModal, prompt } from '@vben/common-ui'
import { Button, message, Tag, Select, DatePicker, Input, Modal, Cascader } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getGoodsPurchaseTotalSkuList, exportData, exportData2, getGoodsCategoryOptions, getGoodsTimeCategoryOptions, saveSearchTemplate, getSearchTemplateList } from '#/api/backend/goodsPurchaseTotalSku'
import { useDebounceFn } from '@vueuse/core'
import dayjs from 'dayjs'
import DeadlineFormComponent from './modules/deadlineForm.vue'
import ExportOrderFormComponent from './modules/exportOrderForm.vue'
import SearchTemplate from '../modules/searchTemplate.vue'
import SearchTemplateSelect from '../modules/SearchTemplateSelect.vue'

interface RowType {
  [key: string]: any
}

const selectedRows = ref<RowType[]>([])
const search_template_list = ref<any[]>([])

const category_options = ref([])
const time_category_options = ref([])

// 获取和设置货品分类选项
const fetchGoodsCategoryOptions = async () => {
  const { list } = await getGoodsCategoryOptions({})
  category_options.value = list
}

// 获取和设置时间分类选项
const fetchGoodsTimeCategoryOptions = async () => {
  const { list } = await getGoodsTimeCategoryOptions({})
  time_category_options.value = list
}

// 初始化分类选项
fetchGoodsCategoryOptions()
fetchGoodsTimeCategoryOptions()

// 在组件挂载后动态更新Cascader选项
onBeforeMount(() => {
  // 初始化获取选项并更新到表单
  fetchGoodsCategoryOptions().then(() => {
    if (gridApi && gridApi.formApi) {
      gridApi.formApi.updateSchema([
        {
          fieldName: 'category',
          componentProps: {
            options: category_options.value || [],
          },
        },
      ])
    }
  })

  fetchGoodsTimeCategoryOptions().then(() => {
    if (gridApi && gridApi.formApi) {
      gridApi.formApi.updateSchema([
        {
          fieldName: 'time_category',
          componentProps: {
            options: time_category_options.value || [],
          },
        },
      ])
    }
  })
})

const params = ref<any>({ quick_search: '' })

// 获取筛选条件列表
const getSearchTemplate = () => {
  getSearchTemplateList({ group_name: 'goodsPurchaseTotalSku' })
    .then((res) => {
      search_template_list.value = res.data || []
    })
    .catch(() => {
      search_template_list.value = []
    })
}
getSearchTemplate()

const saveWhere = async () => {
  prompt<string>({
    componentProps: {},
    title: '保存搜索条件',
    content: '自定义名称',
    // icon: 'question',
    overlayBlur: 3,
  })
    .then(async (res) => {
      // message.success(`用户输入了：${res}`)
      if (res) {
        const formValues = await gridApi.formApi.getValues()
        // 将对象转换为数组格式
        // const contentArray = Object.entries(formValues).map(([key, value]) => ({
        //   key,
        //   value,
        // }))
        saveSearchTemplate({
          title: res,
          data_type: 'goodsPurchaseTotalSku',
          group_name: 'goodsPurchaseTotalSku',
          content: formValues,
        }).then(() => {
          message.success('保存成功')
        })
      }
    })
    .catch(() => {
      message.error('用户取消了输入')
    })
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'goods_purchase_sn',
      label: '采购单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入采购单号',
      },
    },
    {
      component: 'Input',
      fieldName: 'goods_no',
      label: '货号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入货号',
      },
    },
    {
      component: 'Input',
      fieldName: 'goods_code',
      label: '简码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入简码',
      },
    },
    {
      component: 'Input',
      fieldName: 'no_has_sku_num',
      label: '未分码数',
      operator: '=',
      componentProps: {
        allowClear: true,
        placeholder: '',
      },
    },
    {
      component: 'Cascader',
      fieldName: 'category',
      label: '货品分类',
      operator: '123',
      componentProps: {
        options: [],
        allowClear: true,
        multiple: true,
        showSearch: true,
        alwaysLoad: true,
        maxTagCount: 'responsive',
        showCheckedStrategy: Cascader.SHOW_CHILD,
      },
    },
    {
      component: 'Cascader',
      fieldName: 'time_category',
      label: '时间分类',
      operator: '123',
      componentProps: {
        options: [],
        allowClear: true,
        multiple: true,
        showSearch: true,
        alwaysLoad: true,
        maxTagCount: 'responsive',
        showCheckedStrategy: Cascader.SHOW_CHILD,
      },
    },
    {
      component: 'Select',
      fieldName: 'is_completed',
      label: '状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        placeholder: '请选择状态',
        options: [
          { label: '未完成', value: 0 },
          { label: '已完成', value: 1 },
        ],
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'purchase_date',
      label: '采购时间',
      operator: 'RANGE',
      render: 'datestring',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
        placeholder: ['开始日期', '结束日期'],
      },
    },
    {
      component: 'Select',
      fieldName: 'purchase_type',
      label: '采购性质',
      operator: 'IN',
      componentProps: {
        allowClear: true,
        placeholder: '请选择采购性质',
        mode: 'multiple',
        maxTagCount: 'responsive',
        options: [
          { label: '成品#首单', value: '8' },
          { label: '加工#补单', value: '9' },
          { label: '加工#首单', value: '10' },
          { label: '成品#补单', value: '11' },
          { label: '成品#加单', value: '12' },
          { label: '加工#加单', value: '13' },
        ],
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
   checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'uni_key',
    isHover: true,
  },
  columnConfig: { useKey: true, resizable: true },
  height: 'auto',
  keepSource: true,
  pagerConfig: { pageSize: 20 },
  columns: [
    { type: 'checkbox', width: 50 },
    { field: 'WarehouseName', width: 90, title: '仓库名称', showOverflow: true },
    { field: 'goods_purchase_sn', width: 120, title: '采购单号', showOverflow: true },
    { field: 'goods_no', width: 90, title: '货号', showOverflow: true },
    { field: 'goods_code', width: 80, title: '简码', showOverflow: true },
    { field: 'year', width: 60, title: '年份', showOverflow: true },
    { field: 'season', width: 60, title: '季节', showOverflow: true },
    { field: 'time_category_name', width: 60, title: '波段', showOverflow: true },
    { field: 'category1', width: 90, title: '一级分类', showOverflow: true },
    { field: 'category2', width: 100, title: '二级分类', showOverflow: true },
    { field: 'category3', width: 90, title: '分类', showOverflow: true },
    { field: 'goods_name', width: 120, title: '货号名称', showOverflow: true },
    { field: 'color_desc', width: 60, title: '颜色', showOverflow: true },
    { field: 'planning_style', width: 90, title: '企划风格', showOverflow: true },
    { field: 'style2', width: 90, title: '二级风格', showOverflow: true },
    { field: 'sq_name', width: 80, title: '深浅色', showOverflow: true },
    { field: 'sexi', width: 60, title: '色系', showOverflow: true },
    { field: 'segan', width: 60, title: '色感', showOverflow: true },
    { field: 'age_name', width: 80, title: '适龄段', showOverflow: true },
    { field: 'shishangdu', width: 80, title: '时尚度', showOverflow: true },
    { field: 'banxing', width: 60, title: '版型', showOverflow: true },
    { field: 'houdu', width: 60, title: '厚度', showOverflow: true },
    { field: 'style3', width: 60, title: '风格', showOverflow: true },
    { field: 'supply_name', width: 80, title: '供应商', showOverflow: true },
    { field: 'price', width: 70, title: '采购价', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'ls_price', width: 70, title: '零售价', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'is_completed', width: 90, title: '状态', showOverflow: true, slots: { default: 'status' } },
    { field: 'created_time', width: 150, title: '下单时间', showOverflow: true},
    { field: 'purchase_date', width: 100, title: '采购时间', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? dayjs(cellValue).format('YYYY-MM-DD') : '-') },
    { field: 'expected_completion_date', width: 100, title: '总交期', showOverflow: true },
    { field: 'fo_dead_line', width: 100, title: '分仓交期', showOverflow: true },
    { field: 'go_dead_line', width: 100, title: '商企要求交期', showOverflow: true },
    { field: 'ph_remark', width: 120, title: '铺货备注(单组合)', showOverflow: true },
    { field: 'ph_remark2', width: 100, title: '铺货备注', showOverflow: true },
    { field: 'windows_remark', width: 120, title: '窗数等级备注', showOverflow: true },
    { field: 'use_shop_level', width: 100, title: '店铺等级', showOverflow: true },
    { field: 'purchase_type', width: 100, title: '采购性质', showOverflow: true, slots: { default: 'purchaseType' } },
    { field: 'plan_total_num', width: 90, title: '采购数量', showOverflow: true },
    { field: 'no_has_sku_num', width: 80, title: '未分码数', showOverflow: true },
    { field: 'plan_total_price', width: 90, title: '采购成本额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'ls_total_price', width: 90, title: '零售成本额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'cuted_num', width: 80, title: '裁床数', showOverflow: true },
    { field: 'cuted_total_price', width: 80, title: '裁床成本额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'ls_cuted_total_price', width: 90, title: '裁床零售额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'zt_num', width: 80, title: '采购在途数', showOverflow: true },
    { field: 'zt_total_price', width: 80, title: '在途成本额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'ls_zt_total_price', width: 80, title: '在途零售额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'reviced_num', width: 80, title: '入库数', showOverflow: true },
    { field: 're_total_price', width: 80, title: '入库成本额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'ls_re_total_price', width: 80, title: '入库零售额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'pro_num', width: 80, title: '生产中数', showOverflow: true },
    { field: 'pro_total_price', width: 80, title: '生产中成本额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'ls_pro_total_price', width: 80, title: '生产中零售额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'no_reviced_num', width: 80, title: '未到货数', showOverflow: true },
    { field: 'no_reviced_total_price', width: 90, title: '未到货成本额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
    { field: 'ls_no_reviced_total_price', width: 90, title: '未到货零售额', showOverflow: true, formatter: ({ cellValue }) => (cellValue ? Number(cellValue).toFixed(2) : '-') },
  ],
  exportConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const { list, total } = await getGoodsPurchaseTotalSkuList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
        })
        return { items: list, total: total }
      },
    },
    sort: true,
  },
  sortConfig: { defaultSort: { field: 'id', order: 'desc' }, remote: true },
  toolbarConfig: { custom: true, export: true, refresh: true, resizable: true, search: true, zoom: true },
  id: 'goods_purchase_total_sku_list',
  customConfig: {
    storage: true,
  },
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})

// 处理导出报表
const handleExportData = async () => {
  const search = await gridApi.formApi.getFiltersValues()
  try {
    await exportData({ export: true, tableSize: 'small', search })
    message.success('已进入导出队列，稍后在导出中心下载')
  } catch (error) {}
}

// 处理直接导出报表
const handleExportData2 = async () => {
  const search = await gridApi.formApi.getFiltersValues()
  try {
    await exportData2({ search, is_exp: 1 })
  } catch (error) {
    message.error('导出失败')
  }
}
// 搜索条件选择框改变时，获取搜索条件内容
const changeWhere = async (value: any, content?: any) => {
  if (value && content) {
    // 将content中的key里的.替换为*
    const processedContent: any = {}
    Object.keys(content).forEach((key) => {
      const newKey = key.replace(/\./g, '*')
      processedContent[newKey] = content[key]
    })
    await gridApi.formApi.resetForm()
    await gridApi.formApi.setValues(processedContent)
  }
}

const fetchData = async () => {
  gridApi.reload()
}

// 登记交期弹窗
const [DeadlineModal, DeadlineModalApi] = useVbenModal({
  connectedComponent: DeadlineFormComponent,
})

// 处理登记交期
const handleShowDeadlineForm = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择数据')
    return
  }
  DeadlineModalApi.setData(selectedRows.value).open()
}

// 导出补单数据弹窗
const [ExportOrderModal, ExportOrderModalApi] = useVbenModal({
  connectedComponent: ExportOrderFormComponent,
})

// 处理导出补单数据
const handleShowExportOrderForm = () => {
  ExportOrderModalApi.open()
}

// 条件管理弹窗
const [SearchTemplateModal, SearchTemplateModalApi] = useVbenModal({
  connectedComponent: SearchTemplate,
})

// 显示条件管理
const showSearchTemplate = () => {
  SearchTemplateModalApi.open()
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button @click="handleExportData" type="ghost" class="mr-2 bg-[#24b916] text-white hover:opacity-75">导出报表</Button>
        <Button @click="handleExportData2" type="ghost" class="mr-2 bg-[#1670b9] text-white hover:opacity-75">直接导出报表</Button>
        <Button @click="handleShowDeadlineForm" type="ghost" class="mr-2 bg-[#b99b16] text-white hover:opacity-75">登记交期</Button>
        <Button @click="handleShowExportOrderForm" type="ghost" class="mr-2 bg-[#807812] text-white hover:opacity-75">导出补单数据</Button>
        <Button type="ghost" class="mr-2 bg-[#16b9b1] text-white hover:opacity-75" @click="showSearchTemplate">条件管理</Button>
        <Button type="ghost" class="mr-2 bg-[#3c72e6] text-white hover:opacity-75" @click="saveWhere">保存条件</Button>
        <div>
          <SearchTemplateSelect @change="changeWhere" :queryData="{ op: 'goodsPurchaseTotalSku' }" />
        </div>
      </template>
      <template #status="{ row }">
        <Tag :color="row.is_completed == 0 ? 'red' : 'green'">
          {{ row.is_completed == 0 ? '未完成' : '已完成' }}
        </Tag>
      </template>

      <template #purchaseType="{ row }">
        <Tag :color="getPurchaseTypeColor(row.purchase_type)">
          {{ getPurchaseTypeText(row.purchase_type) }}
        </Tag>
      </template>
    </Grid>
    <DeadlineModal @fetch-data="fetchData" />
    <ExportOrderModal />
    <SearchTemplateModal @fetch-data="getSearchTemplate" />
  </Page>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

// 采购性质映射
const purchaseTypes: Record<string, string> = {
  8: '成品#首单',
  9: '加工#补单',
  10: '加工#首单',
  11: '成品#补单',
  12: '成品#加单',
  13: '加工#加单',
}

const getPurchaseTypeColor = (type: string | number) => {
  const numType = Number(type)
  if ([8, 11, 12].includes(numType)) return 'blue'
  if ([9, 10, 13].includes(numType)) return 'orange'
  return 'default'
}

const getPurchaseTypeText = (type: string | number) => {
  return purchaseTypes[String(type)] || '未知'
}

export default defineComponent({
  name: 'GoodsPurchaseTotalSku',
})
</script>
